import React, { PureComponent, useEffect, useState } from 'react';
import {
    InputComp,
    DetailTable,
    ComponentType,
    PmActivityTable, ComboBox, GlobalProvider,
} from 'jh-lib';

import { getRandomKey, sleepFunc, jhMultiply } from 'jh-utils';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import { find, isEmpty, isFunction, map } from 'lodash-es';
import finderConfJson from '../../FinderSelect/finderConf';
import { Button, Card, Form } from 'antd';
import { addrCreateApi, addrGetByParent, addrMsgApi, finderConfApi } from '../../Config/GlobalApi';

dayjs.extend(utc);

let disabled = false;

const actionConf = {
    addable: true,
    deletable: true,
    editable: true,
    fieldName: 'details',
    keyField: 'finder',
    required: true,
    standard: true,
};

let startIndex = 0;

const requestObj = {
    reqGet: (api, data) => {
        console.log('reqGet', api, data);
        // 查找器配置
        if (api.indexOf(finderConfApi.api) === 0) {
            return new Promise((resolve, reject) => {
                setTimeout(() => {
                    const res = finderConfJson;
                    resolve(res);
                }, 500);
            });
        }

    },
    jsonPost: (api, ajaxData) => {
        console.log('jsonPost', api, ajaxData);
        return new Promise((resolve) => {

            const arr = [];

            for (let i = ajaxData.startIndex; i < ajaxData.startIndex + ajaxData.maxResults; i++) {
                startIndex++;
                let id = i + 1;
                arr.push(
                    { id: id, code: `code${id}`, name: `name${id}`, spellCode: `spellCode${id}` },
                );
            }

            setTimeout(() => {
                resolve({
                    status: 200,
                    data: {
                        results: arr,
                        resultCount: 100,
                        maxResults: 20,
                    },
                });
            }, 300);
        });
    },
};

class test extends PureComponent {

    detailFieldInsObj = {};
    state = {};

    componentDidMount() {
        console.log('mounted');
        this.setBodyEditAfterHandler('detail', 'text', (value, record) => {
            let generalVal = null;
            switch (value) {
                case 'finder':
                    generalVal = { componentType: ComponentType.FINDER, finder: 'USER' };
                    break;
                case 'combo':
                    generalVal = { componentType: ComponentType.COMBO_BOX };
                    break;
                case 'number':
                    generalVal = { componentType: ComponentType.NUMBER_INPUT };
                    break;
                case 'text':
                    generalVal = { componentType: ComponentType.TEXT_INPUT };
                    break;
                case 'embed':
                    generalVal = { componentType: ComponentType.EMBED_SELECTOR, selector: 'TEST' };
                    break;
            }
            record.general = generalVal;
        });
        // this.setBodyEditBeforeHandler('detail', 'general', (compIns) => {
        //     let record = this.getBodyRecordByIns(compIns);
        //     console.log('general before', compIns)
        //
        //     switch (record.text) {
        //         case 'finder':
        //             compIns.setCompProps({componentType: ComponentType.FINDER});
        //             break;
        //         case 'combo':
        //             compIns.setCompProps({componentType: ComponentType.COMBO_BOX});
        //             break;
        //         case 'number':
        //             compIns.setCompProps({componentType: ComponentType.NUMBER_INPUT});
        //             break;
        //         case 'text':
        //             compIns.setCompProps({componentType: ComponentType.TEXT_INPUT});
        //             break;
        //         case 'embed':
        //             compIns.setCompProps({
        //                 componentType: ComponentType.EMBED_SELECTOR,
        //                 selector: 'TEST'
        //             });
        //             break;
        //     }
        // });

        this.setBodyEditBeforeHandler('detail', 'objectEnum', (ins) => {
            ins.setCompProps({
                fetchList: (ajaxData) => {
                    return new Promise((resolve) => {
                        sleepFunc(500).then(() => {
                            resolve({
                                status: 200,
                                data: [
                                    { id: 1, code: 'code1', name: 'name1' },
                                    { id: 2, code: 'code2', name: 'name2' },
                                ],
                            });
                        });
                    });
                },
            });
        });

        // this.setBodyEditAfterHandler('detail', 'type', (value, record) => {
        //     record.RANDOM = getRandomKey();
        // });

        // this.setBodyEditAfterHandler('detail', 'checkBox', (value, record) => {
        //     record.type = {};
        // });
        // this.setBodyEditAfterHandler('detail', 'text', (value, record) => {
        //     record.type = null;
        // });
        this.setState({ randomKey: getRandomKey() });
    }

    fetchCombo(ajaxData) {
        return new Promise(resolve => {
            sleepFunc(300).then(() => {
                resolve({
                    status: 200, data: {
                        options: [
                            { code: 'reader', name: '读者' },
                            { code: 'writer', name: '作者' },
                        ],
                    },
                });
            });
        });
    }

    /**
     * 根据 fieldName 将对应的【字段组件】的实例，设置到 detailFieldInsObj 变量中
     * @param fieldName 字段名
     * @param ins 【字段组件】 的实例
     * @param customprops object 给 UIReleaseVersion 传入的 customprops 属性
     */
    setFieldInsByName(fieldName, ins, customprops) {
        if (!isEmpty(fieldName)) {
            this.detailFieldInsObj[fieldName] = ins;
        }
        // console.log('setFieldInsByName', fieldName, ins, this.detailFieldInsObj);
    }

    /**
     * 获取“表单-字段”的组件实例
     * @param fieldName {string}
     * @return {*|{}}
     */
    getFieldIns(fieldName) {
        return this.detailFieldInsObj[fieldName] || {};
    }

    /**
     * 设置“子表-字段-编辑前”事件处理
     * @param body {string}
     * @param fieldName {string}
     * @param func {function(compIns)} // compIns 是当前编辑组件的实例
     */
    setBodyEditBeforeHandler(body, fieldName, func) {
        const bodyIns = this.getFieldIns(body);
        isFunction(bodyIns.addEditBeforeHandler) && bodyIns.addEditBeforeHandler(fieldName, func);
        // const bodyObj = this.getExtraBodyByName(body);
        // bodyObj.befores[fieldName] = func;
    }

    /**
     * 设置“子表-字段-编辑后”事件处理
     * @param body {string}
     * @param fieldName {string}
     * @param func {function(value: any, record: {})} // value 是单元格的值；record 是当前行数据;
     */
    setBodyEditAfterHandler(body, fieldName, func) {
        const bodyIns = this.getFieldIns(body);
        isFunction(bodyIns.addEditAfterHandler) && bodyIns.addEditAfterHandler(fieldName, func);

        // const bodyObj = this.getExtraBodyByName(body);
        // bodyObj.afters[fieldName] = func;
    }

    /**
     * 根据【子表-单元格组件的实例】获取当前的行数据（record）
     * @param compIns {{}} 单元格组件的实例
     * @return {{}}
     */
    getBodyRecordByIns(compIns) {
        let record = {};
        if (compIns && compIns.props && compIns.props.belong) {
            let recordKey = compIns.props.record ? compIns.props.record.key : '';
            let bodyData = this.getBodyData(compIns.props.belong.bodyFieldName);
            if (bodyData) {
                // console.log('recordKey', recordKey, bodyData);
                record = find(bodyData, (v) => (v && v.key === recordKey));
            }
        }
        return record;
    };

    /**
     * 获取子表的 dataSource
     * @param bodyField
     * @return {*}
     */
    getBodyData(bodyField) {
        let ins = this.getFieldIns(bodyField);
        if (ins && ins.getAjaxData) {
            return ins.getAjaxData(false);
        }
    }

    getTmpData() {
        const tdata = [];
        for (let i = 0; i < 2; i++) {
            let k = getRandomKey();
            tdata.push({
                key: k,
                lineKey: k,
                date: (1585741182 + i * 1000) * 1000,
                authorField: {
                    author: true,
                    reader: false,
                },
                amount: i + 1,
                number: jhMultiply((i + 1), Math.random() * 100),
                type: { id: 99, code: 'code99', name: 'name99' },
                note: i % 2 === 0,
                acctFactor: {
                    department: { id: 1, code: 'cod1', name: '部门1' },
                    resourceTarget: { id: 1, code: 'cod1', name: '核算对象1' },
                    resourceItem: { id: 1, code: 'cod1', name: '核算要素1' },
                    project: { id: 1, code: 'cod1', name: '工程项目1' },
                },
            });
        }
        return tdata;
    }

    render() {
        const cols = [
            {
                remark: 'Key',
                name: 'key',
                colWidth: 150,
            },
            // {
            //     remark: '权限',
            //     name: 'authorField',
            //     floatNum: '',
            //     sum: false,
            //     reg: '',
            //     expression: '',
            //     align: '',
            //     colWidth: 150,
            //     componentType: ComponentType.EMBED_SELECTOR,
            //     selector: 'TT'
            // },
            // {
            //     remark: 'OBJERCT_ENUM',
            //     name: 'objectEnum',
            //     floatNum: '',
            //     sum: false,
            //     reg: '',
            //     expression: '',
            //     align: '',
            //     colWidth: 150,
            //     componentType: ComponentType.OBJERCT_ENUM
            // },
            {
                remark: 'ORDER',
                name: 'order',
                floatNum: '',
                sum: false,
                reg: '',
                expression: '',
                align: '',
                colWidth: 150,
                componentType: ComponentType.NUMBER_INPUT,
            },
            // {
            //     remark: 'CUST_EMBED_SELECTOR',
            //     name: 'cust_embed_selector',
            //     floatNum: '',
            //     sum: false,
            //     reg: '',
            //     expression: '',
            //     align: '',
            //     colWidth: 150,
            //     componentType: ComponentType.CUST_EMBED_SELECTOR,
            //     selector: '004'
            // },
            {
                remark: '文本',
                name: 'text',
                floatNum: 2,
                sum: false,
                reg: '',
                expression: '',
                format: '',
                align: 'right',
                colWidth: 100,
                componentType: ComponentType.TEXT_INPUT,
            },
            {
                remark: 'GENERAL',
                name: 'general',
                floatNum: '',
                sum: false,
                reg: '',
                expression: '',
                format: '',
                align: '',
                colWidth: 100,
                componentType: ComponentType.GENERAL_COMPONENT,
            },
            {
                remark: 'finder',
                name: 'finder',
                floatNum: '',
                sum: false,
                reg: '',
                expression: '',
                format: '',
                align: '',
                colWidth: 200,
                componentType: 'FINDER',
                finderCode: 'FINDER_ACCOUNTINGITEM',
                appCode: 'ACCOUNTING_ITEM',
                // editable: true,
                // editingSetting: (value, record, rowIndex, moreProps = {}) => {
                // 	// console.log('moreProps', moreProps)
                // 	return {
                // 		// options: {
                // 		//     initialValue: value
                // 		// },
                // 		comp: <FinderSelect
                // 			multi={false}
                // 			defaultOpen={true}
                // 			autoFocus={true}
                // 			finderCode={'FINDER_ACCOUNTINGITEM'}
                // 			appCode={'ACCOUNTING_ITEM'}
                // 			needMenu={true}
                // 			{...moreProps}
                // 		/>,
                // 	};
                // },
            },
            {
                remark: '类型.name',
                name: 'type.name',
                floatNum: 2,
                sum: true,
                reg: '',
                expression: '',
                format: '',
                align: '',
                colWidth: 200,
                componentType: ComponentType.TEXT_INPUT,
            },
            {
                remark: 'NUMBER_INPUT',
                name: 'number',
                floatNum: 6,
                sum: true,
                reg: '',
                expression: '',
                format: '$',
                align: 'right',
                colWidth: 200,
                componentType: ComponentType.NUMBER_INPUT,
            },
            {
                remark: 'CHECK_BOX',
                name: 'checkBox',
                floatNum: '',
                sum: false,
                reg: '',
                expression: '',
                format: '',
                align: '',
                colWidth: 100,
                componentType: ComponentType.CHECK_BOX,
            },
            {
                remark: '操作',
                name: '',
                key: 'action',
                floatNum: '',
                sum: false,
                reg: '',
                expression: '',
                format: '',
                align: '',
                colWidth: 100,
                render: (value, record) => (record.IS_SUM ? null : <a onClick={() => {
                    console.log('a');
                }}>Delete</a>),
            },
        ];

        return (
            <GlobalProvider request={requestObj}>
                <h3>DetailTable</h3>
                <Form layout={'inline'}
                      style={{ marginBottom: 10 }}
                      onFinish={(values) => {
                          console.log('values', values);
                          if (this.tableRef && this.tableRef.setFocusCell) {
                              this.tableRef.setFocusCell({ col: '', row: '' });
                              this.tableRef.setFocusCell(values);
                          }
                      }}>
                    <ComboBox compLabel={'列'} fieldName={'col'}
                              compData={map(cols, item => ({ code: item.name, name: item.remark }))}
                    />
                    <InputComp compLabel={'行'} fieldName={'row'}/>

                    <Form.Item>
                        <Button htmlType={'submit'}>定位到单元格</Button>
                    </Form.Item>
                </Form>
                <div style={{ marginBottom: 8 }}>
                    <Button onClick={() => {
                        let tableIns = this.getFieldIns('detail');
                        if (tableIns && tableIns.setEnabled) {
                            disabled = !disabled;
                            tableIns.setEnabled(!disabled);
                        }
                    }}>setEnabled</Button>&nbsp;&nbsp;
                    <Button onClick={() => {
                        let tableIns = this.getFieldIns('detail');
                        console.log('tableIns', tableIns);
                        if (tableIns && tableIns.setData) {
                            tableIns.setData(this.getTmpData());
                        }
                    }}>setData</Button>&nbsp;&nbsp;
                    <Button onClick={() => {
                        let tableIns = this.getFieldIns('detail');
                        if (tableIns && tableIns.getAjaxData) {
                            const data = tableIns.getAjaxData(false);
                            console.log('tableIns.getAjaxData', data);

                            if (tableIns.refreshWithEmptyRow) {
                                tableIns.refreshWithEmptyRow(data);
                            }
                        }
                    }}>getAjaxData</Button>&nbsp;&nbsp;
                </div>
                <div style={{ height: 400, overflow: 'auto', border: '1px solid #ddd' }}>
                    <DetailTable
                        onRef={(ref) => {
                            this.tableRef = ref;
                        }}
                        style={{ height: 350, width: '100%' }}
                        appins={this}
                        fieldName={'detail'}
                        customprops={{ PAGE_TYPE: 'DETAIL' }}
                        colsConf={cols}
                        actionConf={actionConf}
                        defaultRowCnt={5}
                        // dataSource={[]}
                        // scroll={scroll}
                        needNO={true}
                        canSort={true}
                        rowSelect={true}
                        pagination={{ pageSize: 8 }}
                        // pagination={false}
                        l={1}
                        r={1}
                    />
                </div>
                <hr/>
                <h3>PmActivityTable</h3>
                <PmActivityTable
                    style={{ height: 400 }}
                    appins={this}
                    fieldName={'pmActivity'}
                    customprops={{ PAGE_TYPE: 'DETAIL' }}
                    colsConf={cols}
                />
            </GlobalProvider>
        );
    }
}

export default test;
